#!/bin/bash

# FlowPlan Backend Docker Entrypoint Script

set -e

# 等待数据库就绪
wait_for_db() {
    echo "Waiting for PostgreSQL to be ready..."
    while ! curl -f "http://postgres:5432" 2>/dev/null; do
        echo "PostgreSQL is unavailable - sleeping"
        sleep 2
    done
    echo "PostgreSQL is ready!"
}

# 等待Redis就绪
wait_for_redis() {
    echo "Waiting for Redis to be ready..."
    while ! curl -f "http://redis:6379" 2>/dev/null; do
        echo "Redis is unavailable - sleeping"
        sleep 2
    done
    echo "Redis is ready!"
}

# 输出启动信息
echo "========================================"
echo "FlowPlan Backend Starting..."
echo "========================================"
echo "Java Version: $(java -version 2>&1 | head -n 1)"
echo "Available Memory: $(free -h | grep Mem | awk '{print $2}')"
echo "Available Disk: $(df -h / | tail -1 | awk '{print $4}')"
echo "========================================"

# 等待依赖服务
if [ "${SPRING_DATASOURCE_URL}" ]; then
    wait_for_db
fi

if [ "${SPRING_REDIS_HOST}" ]; then
    wait_for_redis
fi

# 设置默认JVM参数
if [ -z "${JAVA_OPTS}" ]; then
    export JAVA_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC"
fi

echo "Starting application with JAVA_OPTS: ${JAVA_OPTS}"

# 启动Spring Boot应用
exec java ${JAVA_OPTS} \
    -Djava.security.egd=file:/dev/./urandom \
    -Dspring.profiles.active=${SPRING_PROFILES_ACTIVE:-docker} \
    -jar app.jar "$@"